#include "uitoast.h"
#include "cutils.h"

#include <QLabel>
#include <QLayout>
#include <QTimer>

UiToast::UiToast(QWidget *parent) : QWidget(parent)
{
    initUi();
}

void UiToast::setText(const QString &text)
{
    m_tipLabel->setText(text);
    auto width = WidthWithFixString(m_tipLabel->font(),text);
    this->setFixedWidth(width+m_spacing*2);
    this->setFixedHeight(50);
}

void UiToast::showEvent(QShowEvent *e)
{
    //土司提示显示位置
    if(this->parent())
    {
        auto pWidget = (QWidget*)(this->parent());
        if(pWidget)
        {
            int x = (pWidget->width()-this->width())/2;
            int y = pWidget->height()/10;
            m_timer->start();
            this->move(x,y);
        }

    }
    QWidget::showEvent(e);
}

void UiToast::initUi()
{
    this->setWindowFlag(Qt::FramelessWindowHint);
    this->setStyleSheet("background:gray;border-radius:6px;");

    m_tipLabel = new QLabel(this);
    m_tipLabel->setAlignment(Qt::AlignCenter);

    m_mainLayout = new QHBoxLayout(this);
    m_mainLayout->addWidget(m_tipLabel);

    m_timer = new QTimer(this);
    m_timer->setInterval(3000);
    connect(m_timer,&QTimer::timeout,this,[=](){
        this->setVisible(false);
    });
}
